<?php

namespace App\Http\Exports;

use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use App\Model\Base;

class QueryExportDeliveryList implements FromQuery,WithHeadings,WithMapping
{

    use Exportable;

    public function __construct($param)
    {
        $map = [];
        if (!empty($getParam['user_name'])) {
            $map['uo.user_name'] = $getParam['user_name'];
        }
        if (!empty($getParam['storehouse_id'])) {
            $map['uod.warehouse_id'] = $getParam['storehouse_id'];
        }
        if (!empty($getParam['category_id'])) {
            $map['cm.category_id'] = $getParam['category_id'];
        }
        $this->map = $map;
    }

    public function query()
    {
        return Base::query()->from('user_order as uo')
            ->select(DB::raw('uod.deliver_time,uo.name,uod.company_name,uod.courier_number,cm.category_name,gm.goods_name,gm.goods_code,gm.goods_id,uod.color,uod.size,uo.add,uo.order_id,uod.goods_num'))
            ->leftJoin('user_order_detailed as uod', 'uo.order_id', '=', 'uod.order_id')
            ->leftJoin('goods_master as gm', 'uod.goods_id', '=', 'gm.goods_id')
            ->leftJoin('goods_model as gmm', 'gm.goods_id', '=',  DB::raw('gmm.goods_id and gmm.goods_model_id = uod.model_id'))
            ->leftJoin('supplier_master as sm', 'sm.supplier_id', '=', 'gm.supplier_id')
            ->leftJoin('category_master as cm', 'gm.category_id', '=', 'cm.category_id')
            ->orderBy('deliver_time')
            ->where($this->map);
    }

    public function headings(): array
    {
        return [
          '注文番号',
          '請求日',
          '発送先',
          'カテゴリー',
          '商品名',
          '商品コード',
          'カラー/サイズ',
          '出荷数',
          '送り状No',
        ];
    }

    public function map($invoice):array
    {
        return [
            $invoice->order_id,
            $invoice->deliver_time,
            $invoice->add,
            $invoice->category_name,
            $invoice->goods_name,
            $invoice->goods_code,
            $invoice->color.'/'.$invoice->size,
            $invoice->goods_num,
            $invoice->courier_number,

        ];
    }

}
